package purchasePlan

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetPurchasePlanTableDetailByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetPurchasePlanTableDetailByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetPurchasePlanTableDetailByIdApiLogic {
	hostname, _ := os.Hostname()
	return &GetPurchasePlanTableDetailByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetPurchasePlanTableDetailByIdApiLogic) GetPurchasePlanTableDetailByIdApi(req *types.IdReq) (resp *types.GetPurchasePlanDetaiResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	var purchasePlan = make([]types.PurchasePlanResp, 0)
	var ordersList = make([]types.OrdersPurchasePlanResp, 0)
	//1.查询采购计划数据
	purchasePlanEntities, err := dao.PurchasePlanEntity.WithContext(l.ctx).Where(dao.PurchasePlanEntity.ID.Eq(req.Id)).First()
	if err != nil {
		return &types.GetPurchasePlanDetaiResp{
			PurchasePlan: purchasePlan, // 采购计划
			OrdersList:   ordersList,   // 订单列表
		}, nil
	}
	inventoryCount := service.SpuInventoryService.GetAllSpuInventoryApi(l.ctx, accountInfo.EnterpriseId, purchasePlanEntities.SpuID)
	_, err2 := service.PurchaseOrderDetailService.GetByPurchasePlanIdApi(l.ctx, purchasePlanEntities.ID)
	// 查询订单
	purchasePlan = append(purchasePlan, types.PurchasePlanResp{
		ID:                purchasePlanEntities.ID,                                    // 主键id
		OrderNo:           purchasePlanEntities.OrderNo,                               // 操作流水号
		SpuID:             purchasePlanEntities.SpuID,                                 // 商品,关联到spu表主键id
		SnapshotSpuName:   purchasePlanEntities.SnapshotSpuName,                       // 快照商品名称
		SnapshotUnit:      purchasePlanEntities.SnapshotUnit,                          // 快照单位
		RequirementsCount: purchasePlanEntities.RequirementsCount.StringFixed(2),      // 需求数量
		PurchaserCount:    purchasePlanEntities.PurchaserCount.StringFixed(2),         // 采购数量
		Remark:            purchasePlanEntities.Remark,                                // 备注
		IsPurchaseOrder:   int64(k.If(errors.Is(err2, gorm.ErrRecordNotFound), 0, 1)), //  // 是否生成采购单,0表示没有,1表示有
		InventoryCount:    inventoryCount.StringFixed(2),
		LossRate:          purchasePlanEntities.LossRate.StringFixed(2), // 损耗率
	})

	planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailByPlanIdApi(l.ctx, purchasePlanEntities.ID)
	if err == nil && len(planOrdersEntities) > 0 {
		ordersSpuIdList := k.Map(planOrdersEntities, func(item *model.PurchasePlanOrdersEntity, index int) int64 {
			return item.OrdersSpuID
		})
		orderDetailBos, err := service.OrdersSpuService.GetListByIDApi(l.ctx, ordersSpuIdList)
		if err == nil && len(orderDetailBos) > 0 {
			for _, item := range orderDetailBos {
				if item.PurchaseStatus == 30 {
					continue
				}
				order, _ := service.OrdersService.GetDetailByIdApi(l.ctx, item.OrdersID)
				ordersList = append(ordersList, types.OrdersPurchasePlanResp{
					OrdersSpuID:    item.ID, // 主键id
					OrdersDetailID: item.ID, // 主键id
					OrdersId:       item.OrdersID,
					OrderNo:        order.OrderNo,                    // 订单流水号
					CustomerID:     item.CustomerID,                  // 客户id,关联到enterprise_customer表主键id
					CustomerName:   item.CustomerName,                // 门店名称
					Remark:         order.Remark,                     // 订单备注
					TotalCount:     item.RequireCount.StringFixed(2), // 订单商品数量
					UnitName:       item.UnitName,                    // 单位名称
				})
			}
		}
	}
	// 合并订单
	//if purchasePlanEntities.IsMerge == 1 && purchasePlanEntities.Remark != "" {
	//	ordersDetailIdList := k.Map(strings.Split(purchasePlanEntities.Remark, ","), func(item string, index int) int64 {
	//		return cast.ToInt64(item)
	//	})
	//	ordersDetailEntityList, err := dao.OrdersDetailEntity.WithContext(l.ctx).Where(dao.OrdersDetailEntity.ID.In(ordersDetailIdList...)).Find()
	//	if err == nil && len(ordersDetailEntityList) > 0 {
	//		ordersIdList := k.Map(ordersDetailEntityList, func(item *model.OrdersDetailEntity, index int) int64 {
	//			return item.OrdersID
	//		})
	//		ordersEntities, err := dao.OrdersEntity.WithContext(l.ctx).Where(dao.OrdersEntity.ID.In(ordersIdList...)).Find()
	//		var ordersIdGroupMap = make(map[int64]*model.OrdersEntity)
	//		if err == nil && len(ordersEntities) > 0 {
	//			ordersIdGroupMap = k.ToMap(ordersEntities, func(item *model.OrdersEntity) (int64, *model.OrdersEntity) {
	//				return item.ID, item
	//			})
	//		}
	//		for _, item := range ordersDetailEntityList {
	//			ordersEntity, isOk := ordersIdGroupMap[item.OrdersID]
	//			customerEntity, _ := service.EnterpriseCustomerService.GetByIdApi(l.ctx, ordersEntity.CustomerID)
	//			ordersList = append(ordersList, types.OrdersPurchasePlanResp{
	//				OrdersDetailID: item.ID, // 主键id
	//				OrdersId:       k.If(isOk, ordersEntity.ID, 0),
	//				OrderNo:        k.If(isOk, ordersEntity.OrderNo, ""),                 // 订单流水号
	//				CustomerID:     k.If(isOk, ordersEntity.CustomerID, 0),               // 客户id,关联到enterprise_customer表主键id
	//				CustomerName:   k.If(customerEntity != nil, customerEntity.Name, ""), // 门店名称
	//				Remark:         ordersEntity.Remark,                                  // 订单备注
	//				TotalCount:     ordersEntity.TotalCount.StringFixed(2),               // 订单商品数量
	//				UnitName:       item.SnapshotUnit,                                    // 单位名称
	//			})
	//		}
	//	}
	//
	//}
	return &types.GetPurchasePlanDetaiResp{
		PurchasePlan: purchasePlan, // 采购计划
		OrdersList:   ordersList,   // 订单列表
	}, nil
}
